//
//  XXIneractiveTransition.m
//  NYP
//
//  Created by jarze on 2018/6/14.
//  Copyright © 2018年 niuyan.com. All rights reserved.
//

#import "XXIneractiveTransition.h"
#define frameOffset 100

@interface XXIneractiveTransition ()<UIGestureRecognizerDelegate>

@property (nonatomic, weak) UIViewController *vc;
@property (nonatomic, assign) CGFloat percent;

@property(nonatomic,assign)BOOL isPresenting;
@property(nonatomic,strong)UIView *containerView;

@property (nonatomic,strong)UIView *bgView;

@end
@implementation XXIneractiveTransition

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}

- (void)addPanGestureForViewController:(UIViewController *)viewController{
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
    self.vc = viewController;
    pan.delegate = self;
    [viewController.view addGestureRecognizer:pan];
}

/**
 *  手势过渡的过程
 */
- (void)handleGesture:(UIPanGestureRecognizer *)gesture{

    CGFloat transitionY = [gesture translationInView:gesture.view].y;
    _percent = transitionY / UIScreen.mainScreen.bounds.size.height / 4.0;
    switch (gesture.state) {
        case UIGestureRecognizerStateBegan:
            self.interation = YES;
            if (!self.vc.isBeingDismissed) {
                [self.vc dismissViewControllerAnimated:YES completion:nil];
            }
            break;
        case UIGestureRecognizerStateChanged:{
            [self updateInteractiveTransition:_percent];
            break;
        }
        case UIGestureRecognizerStateEnded:{
            self.interation = NO;
            if (_percent > 0.1) {
                [self setCompletionSpeed:1 - _percent];
                [self finishInteractiveTransition];
            }else{
                // 放手取消减速
#warning 有bug
                [self setCompletionSpeed:_percent];
                [self cancelInteractiveTransition];
            }
            break;
        }
        default:
            break;
    }
}

//- (CGFloat)completionSpeed {
//    return self.percentComplete <= 0.1 ? self.percentComplete : 1;
//}

//- (void)startInteractiveTransition:(id<UIViewControllerContextTransitioning>)transitionContext {
//    [super startInteractiveTransition:transitionContext];
//}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
//    if (self.interation) {
//        return YES;
//    }
//    UIView *otherView = otherGestureRecognizer.view;
//    if ([otherView isKindOfClass:[UIScrollView class]]) {
//        UIScrollView *scrollView = (UIScrollView *)otherView;
//        if (scrollView.contentOffset.y < 1 ) {
//            scrollView.userInteractionEnabled = NO;
//            return YES;
//        }
//
//    }
//    return NO;
//}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return YES;
}


//定义一个类的 property,用来区别我们到底现在是 呈现 还是 消失

-(id)initWithBool:(BOOL)ispresenting{
    self = [super init];
    if (self) {
        self.isPresenting = ispresenting;
    }
    return self;
}

#pragma mark - UIViewControllerAnimatedTransitioning

- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext{
    return 0.5f;
}

- (void)animateTransition:(id <UIViewControllerContextTransitioning>)transitionContext{
    if (self.isPresenting) {
        [self presentAnimation:transitionContext];
    }else{
        [self dismissAnimation:transitionContext];
    }
}

//实现present动画逻辑代码
- (void)presentAnimation:(id<UIViewControllerContextTransitioning>)transitionContext {
    self.containerView = [transitionContext containerView];
    
    //创建视图
    self.bgView = [[UIView alloc]initWithFrame: [UIScreen mainScreen].bounds];
    UIVisualEffectView *blurView = [[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    blurView.frame = self.containerView.bounds;
    [self.bgView insertSubview:blurView atIndex:0];
    self.bgView.alpha = 0.0;
    
    UIViewController *toVC = (UIViewController *)[transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    [self.containerView addSubview:self.bgView];
    [self.containerView addSubview:toView];
    
    //设定presented view 一开始的位置，在屏幕下方
    CGRect initialframe = [transitionContext finalFrameForViewController:toVC];
    CGRect startframe = CGRectOffset(initialframe, 0, initialframe.size.height);
    toView.frame = startframe;
    
    CGRect changeSizeFrame = CGRectMake(initialframe.origin.x, initialframe.origin.y + frameOffset, initialframe.size.width, initialframe.size.height - frameOffset);
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.0f usingSpringWithDamping:0.7f initialSpringVelocity:0.0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{
        toView.frame = changeSizeFrame;
        self.bgView.alpha = 0.7;
    } completion:^(BOOL finished) {
        if (finished) {
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }
    }];
}

//实现dismiss动画逻辑代码
- (void)dismissAnimation:(id<UIViewControllerContextTransitioning>)transitionContext{
    self.containerView = [transitionContext containerView];
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    CGRect initialframe = fromView.frame;
    CGRect finalframe = initialframe;
    finalframe.origin.y = self.containerView.bounds.size.height;
    // 添加一个动画，让要消失的 view 向下移动，离开屏幕
    [UIView animateWithDuration:[self transitionDuration:transitionContext] delay:0.3f usingSpringWithDamping:0.7f initialSpringVelocity:0.0 options:UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionCurveLinear animations:^{
        //secondviewcontroller 滑下去
        fromView.frame = finalframe;
        self.bgView.alpha = 0;
    } completion:^(BOOL finished) {
        if (finished) {
            BOOL cancel = [transitionContext transitionWasCancelled];
            if (!cancel) {
                [self.bgView removeFromSuperview];
            }
            [transitionContext completeTransition:!cancel];
        }
    }];
}

- (void)animationEnded:(BOOL) transitionCompleted {
    if (transitionCompleted) {
        
    } else {
        
    }
}

#pragma mark - UIViewControllerTransitioningDelegate

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source {
    self.isPresenting = YES;
    return self;
}

- (id<UIViewControllerInteractiveTransitioning>)interactionControllerForPresentation:(id<UIViewControllerAnimatedTransitioning>)animator {
    self.isPresenting = YES;
    return self;
}

- (id <UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed {
    if (dismissed) {
        self.isPresenting = NO;
        return self;
    } else {
        return nil;
    }
}

- (id <UIViewControllerInteractiveTransitioning>)interactionControllerForDismissal:(id<UIViewControllerAnimatedTransitioning>)animator {
    if (self.interation) {
        self.isPresenting = NO;
        return self;
    }else{
        return nil;
    }
}
@end
